import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  Alert,
  KeyboardAvoidingView,
  Platform,
  ActivityIndicator,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { useTheme } from '../../contexts/ThemeContext';
import { AuthStackParamList } from '../../navigation/AuthNavigator';
import { authAPI } from '../../services/api';

type RegisterScreenNavigationProp = StackNavigationProp<AuthStackParamList, 'Register'>;

const RegisterScreen: React.FC = () => {
  const navigation = useNavigation<RegisterScreenNavigationProp>();
  const { colors } = useTheme();
  
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  const handleRegister = async () => {
    // 输入验证
    if (!name.trim()) {
      Alert.alert('错误', '请输入姓名');
      return;
    }

    if (!email.trim()) {
      Alert.alert('错误', '请输入邮箱地址');
      return;
    }

    if (!password.trim()) {
      Alert.alert('错误', '请输入密码');
      return;
    }

    if (!confirmPassword.trim()) {
      Alert.alert('错误', '请确认密码');
      return;
    }

    // 邮箱格式验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email.trim())) {
      Alert.alert('错误', '请输入正确的邮箱格式');
      return;
    }

    // 密码长度验证
    if (password.length < 6) {
      Alert.alert('错误', '密码长度至少6位');
      return;
    }

    // 密码一致性验证
    if (password !== confirmPassword) {
      Alert.alert('错误', '两次输入的密码不一致');
      return;
    }

    // 密码强度验证
    const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/;
    if (!passwordRegex.test(password)) {
      Alert.alert('错误', '密码必须包含大小写字母和数字');
      return;
    }

    setIsLoading(true);

    try {
      // 调用真实注册API
      const response = await authAPI.register(name.trim(), email.trim(), password);
      
      if (response.data.success) {
        Alert.alert('成功', '注册成功！请登录您的账户', [
          { 
            text: '确定', 
            onPress: () => navigation.navigate('Login') 
          }
        ]);
      } else {
        throw new Error(response.data.message || '注册失败');
      }
    } catch (error: any) {
      let errorMessage = '注册失败，请重试';
      
      if (error.response) {
        // 服务器返回错误
        const status = error.response.status;
        if (status === 400) {
          if (error.response.data.message?.includes('邮箱')) {
            errorMessage = '该邮箱已被注册';
          } else if (error.response.data.message?.includes('密码')) {
            errorMessage = '密码格式不正确';
          } else {
            errorMessage = error.response.data.message || '请求参数错误';
          }
        } else if (status === 409) {
          errorMessage = '该邮箱已被注册';
        } else if (status === 500) {
          errorMessage = '服务器内部错误，请稍后重试';
        } else if (status === 0 || status === 'NETWORK_ERROR') {
          errorMessage = '网络连接失败，请检查网络设置';
        }
      } else if (error.request) {
        // 网络请求失败
        errorMessage = '网络连接失败，请检查网络设置';
      } else if (error.message) {
        // 其他错误
        errorMessage = error.message;
      }
      
      Alert.alert('注册失败', errorMessage);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <KeyboardAvoidingView 
      style={[styles.container, { backgroundColor: colors.background }]}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <View style={styles.content}>
        <Text style={[styles.title, { color: colors.text }]}>创建账户</Text>
        <Text style={[styles.subtitle, { color: colors.textSecondary }]}>
          请填写以下信息完成注册
        </Text>

        <View style={styles.form}>
          <TextInput
            style={[styles.input, { 
              backgroundColor: colors.surface,
              color: colors.text,
              borderColor: colors.border,
            }]}
            placeholder="姓名"
            placeholderTextColor={colors.textSecondary}
            value={name}
            onChangeText={setName}
            editable={!isLoading}
          />

          <TextInput
            style={[styles.input, { 
              backgroundColor: colors.surface,
              color: colors.text,
              borderColor: colors.border,
            }]}
            placeholder="邮箱"
            placeholderTextColor={colors.textSecondary}
            value={email}
            onChangeText={setEmail}
            keyboardType="email-address"
            autoCapitalize="none"
            autoCorrect={false}
            editable={!isLoading}
          />

          <TextInput
            style={[styles.input, { 
              backgroundColor: colors.surface,
              color: colors.text,
              borderColor: colors.border,
            }]}
            placeholder="密码"
            placeholderTextColor={colors.textSecondary}
            value={password}
            onChangeText={setPassword}
            secureTextEntry
            editable={!isLoading}
          />

          <TextInput
            style={[styles.input, { 
              backgroundColor: colors.surface,
              color: colors.text,
              borderColor: colors.border,
            }]}
            placeholder="确认密码"
            placeholderTextColor={colors.textSecondary}
            value={confirmPassword}
            onChangeText={setConfirmPassword}
            secureTextEntry
            editable={!isLoading}
          />

          <TouchableOpacity
            style={[
              styles.registerButton, 
              { 
                backgroundColor: isLoading ? colors.border : colors.primary,
                opacity: isLoading ? 0.7 : 1
              }
            ]}
            onPress={handleRegister}
            disabled={isLoading}
          >
            {isLoading ? (
              <ActivityIndicator color="#FFFFFF" size="small" />
            ) : (
              <Text style={styles.registerButtonText}>注册</Text>
            )}
          </TouchableOpacity>

          <View style={styles.loginContainer}>
            <Text style={[styles.loginText, { color: colors.textSecondary }]}>
              已有账户？
            </Text>
            <TouchableOpacity onPress={() => navigation.navigate('Login')} disabled={isLoading}>
              <Text style={[styles.loginLink, { color: colors.primary }]}>
                立即登录
              </Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  content: {
    flex: 1,
    justifyContent: 'center',
    paddingHorizontal: 20,
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 16,
    textAlign: 'center',
    marginBottom: 40,
  },
  form: {
    width: '100%',
  },
  input: {
    height: 50,
    borderWidth: 1,
    borderRadius: 8,
    paddingHorizontal: 16,
    marginBottom: 16,
    fontSize: 16,
  },
  registerButton: {
    height: 50,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 8,
  },
  registerButtonText: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: '600',
  },
  loginContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 40,
  },
  loginText: {
    fontSize: 14,
  },
  loginLink: {
    fontSize: 14,
    fontWeight: '600',
    marginLeft: 4,
  },
});

export default RegisterScreen; 